/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.io.*;
import com.lowagie.text.DocumentException;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;
import org.xhtmlrenderer.pdf.ITextRenderer;

/**
 *
 * @author wei
 */
public class PDFGenerator {

    public static String generatePDFFromUrl(HttpServletRequest request, String page, Long id, Long name) {
        OutputStream os = null;
        try {
            String pdfName = name == null ? id.toString() : name.toString();
            System.out.println(" in PDFGenerator: generating pdf");
            System.out.println("current dir: " + System.getProperty("user.dir"));
            String url = new URL(getWebPdfFolderPath(request) + page + "?id=" + id).toString();
            String outputFile = pdfName + ".pdf";
            os = new FileOutputStream(outputFile);

            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(url);
            renderer.layout();
            renderer.createPDF(os);
            os.close();

            String pwd = System.getProperty("user.dir");

            return pwd + getSlash() + pdfName + ".pdf";
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        return "";
    }

    public static String getFilePdfFolderPath(long id) {
        return System.getProperty("user.dir") + getSlash() + id + ".pdf";
    }

    public static String getWebPdfFolderPath(HttpServletRequest request) {
        String path = request.getContextPath();

        String getProtocol = request.getScheme();
        String getDomain = request.getServerName();
        String getPort = Integer.toString(request.getServerPort());

        String getPath = getProtocol + "://" + getDomain + ":" + getPort + path + "/pdf/";

        return getPath;
    }

    private static String getSlash() {
        String pwd = System.getProperty("user.dir");
        String slash;
        if (pwd.indexOf("\\") > 0) {
            slash = "\\";
        } else {
            slash = "/";
        }
        return slash;
    }
}
